package cn.wildfire.chat.app.main;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sourcemuch.im.caiba.CaiBaChatApp;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.R2;
import com.sourcemuch.im.caiba.wxapi.WXUserInfo;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.OnClick;
import cn.wildfire.chat.app.extendsion.classes.AccountSecurityCheckRequest;
import cn.wildfire.chat.app.extendsion.classes.BindWeiXinRequest;
import cn.wildfire.chat.app.extendsion.classes.SecurityStatus;
import cn.wildfire.chat.app.extendsion.ui.CustomAppUIDialog;
import cn.wildfire.chat.app.extendsion.ui.TipDialog;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.OSHelper;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.login.SMSLoginActivity;
import cn.wildfire.chat.kit.WfcBaseActivity;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.model.UserInfoExtra;

/**
 * Create by HEKE, 2019/10/16 18:55
 * TODO 账号与安全界面
 */
public class AccountSecurityActivity extends WfcBaseActivity implements
        AccountSecurityCheckRequest.OnAccountSecurityCheckListener,
        BindWeiXinRequest.OnBinWeiXinListener {

    // 绑定手机号请求
    public static final int REQUEST_BIND_PHONE = 1000;
    // 设置密保问题
    public static final int REQUEST_SET_SECURITY_QUESTION = 1001;
    // 修改密码
    public static final int REQUEST_MODIFY_PASSWORD = 1002;

    @BindView(R2.id.xintuiNumber)
    TextView xintuiNumber;
    @BindView(R2.id.xintuiLayout)
    RelativeLayout xintuiLayout;
    @BindView(R2.id.phoneNumber)
    TextView phoneNumber;
    @BindView(R2.id.phoneLayout)
    RelativeLayout phoneLayout;
    @BindView(R2.id.xintuiPasswordNumber)
    TextView xintuiPasswordNumber;
    @BindView(R2.id.xintuiPasswordLayout)
    RelativeLayout xintuiPasswordLayout;
    @BindView(R2.id.xintuiSecurityNumber)
    TextView xintuiSecurityNumber;
    @BindView(R2.id.xintuiSecurityLayout)
    RelativeLayout xintuiSecurityLayout;
    @BindView(R2.id.xintuiBindNumber)
    TextView xintuiBindNumber;
    @BindView(R2.id.xintuiWeiXinLayout)
    RelativeLayout xintuiWeiXinLayout;

    private UserViewModel userViewModel;
    private UserInfo userInfo;

    protected SecurityStatus securityStatus;

    /**
     * 绑定微信对象
     */
    protected BindWeiXinRequest bindWeiXinRequest;

    private void requestStatus() {
        if (userInfo == null)
            return;
        new AccountSecurityCheckRequest(this, userInfo.uid, this);
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_account_security;
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 2);
        setReplaceTitle(null, R.string.account_and_security);
        setSearchLayoutVisibility(false);
        userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
        userInfo = userViewModel.getUserInfo(userViewModel.getUserId(), true);
        requestStatus();
        initViews();
    }

    private void initViews() {
        if (userInfo != null) {
            if (!TextUtils.isTextEmpty(userInfo.extra)) {
                UserInfoExtra userInfoExtra = new Gson().fromJson(userInfo.extra, UserInfoExtra.class);
                xintuiNumber.setText("" + userInfoExtra.getCaiba_number());
            }
        }
        bindWeiXinRequest = new BindWeiXinRequest(this, this);
    }

    // 界面暂停过
    protected boolean havePaused;
    // 绑定微信请求标记
    protected boolean bindWeiXinRequested;

    @Override
    protected void onResume() {
        super.onResume();
        try {
            limitActivityCount = false;
            if (havePaused) {
                havePaused = false;
                requestStatus();
            }
            // 绑定微信请求
            if (bindWeiXinRequested) {
                bindWeiXinRequested = false;
                WXUserInfo wxUserInfo = ((CaiBaChatApp) getApplicationContext()).wxUserInfo;
                if (wxUserInfo != null) {
                    wxUserInfo.uid = userViewModel.getUserId();
                    bindWeiXinRequest.req(this, wxUserInfo);
                }
            }
            // 检测微信是否安装，未安装隐藏微信绑定选项
            if (!OSHelper.checkApkExist(this, OSHelper.WX_APP_PACKAGENAME)) {
                xintuiWeiXinLayout.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        havePaused = true;
    }

    @Override
    public void result(SecurityStatus securityStatus) {
        this.securityStatus = securityStatus;
        refreshUI();
    }

    // 界面刷新
    protected void refreshUI() {
        if (securityStatus != null) {
            // 手机号绑定设置
            phoneNumber.setText((securityStatus.checkBindMobile == 1) ? "" + securityStatus.mobile : getString(R.string.none_bind));
            // 密码设置
            xintuiPasswordNumber.setText((securityStatus.checkExistsPassword == 1) ? getString(R.string.hava_setting) : getString(R.string.none_setting));
            // 密保设置
            xintuiSecurityNumber.setText((securityStatus.checkExistsEncrypted == 1) ? getString(R.string.hava_setting) : getString(R.string.none_setting));
            // 微信号绑定设置
            xintuiBindNumber.setText((securityStatus.checkBindWX == 1) ? getString(R.string.hava_bind) : getString(R.string.none_bind));
        }
    }

    /**
     * 手机号绑定
     */
    private void bindPhoneReq() {
        try {
            if (!limitActivityCount) {
                limitActivityCount = true;
                Intent bindOrModifyPhoneNumberIntent = new Intent(this, SMSLoginActivity.class);
                bindOrModifyPhoneNumberIntent.putExtra("userInfo", userInfo);
                bindOrModifyPhoneNumberIntent.putExtra("phone", securityStatus.mobile);
                bindOrModifyPhoneNumberIntent.putExtra("havaBindPhone", securityStatus.checkBindMobile == 1);
                startActivityForResult(bindOrModifyPhoneNumberIntent, REQUEST_BIND_PHONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 未绑定手机号，优先绑定提示窗口
     *
     * @param type 0密码，1密保，2微信
     */
    private boolean firstBindPhoneNumberCheck(int type) {
        if (securityStatus == null)
            return false;
        boolean need = (securityStatus.checkBindMobile == 0);
        if (need) {
            String content = "";
            switch (type) {
                case 0:
                    content = getString(R.string.set_password_need_bind_phonenumber_msg);
                    break;
                case 1:
                    content = getString(R.string.set_security_need_bind_phonenumber_msg);
                    break;
                case 2:
                    content = getString(R.string.set_weixin_need_bind_phonenumber_msg);
                    break;
                default:
                    break;
            }
            TipDialog.showCustomDialog(this, getString(R.string.wendy_title), content, new String[]{getString(R.string.confirm), getString(R.string.cancle_but)},
                    CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true, 2, true, new TipDialog.OnMsgTipDialogListener() {
                        @Override
                        public void then(boolean confirm, boolean outtouch) {
                            if (confirm) {
                                bindPhoneReq();
                            }
                        }
                    });
        }
        return need;
    }

    // 限制快速点击跳转页面出现多个情况
    protected boolean limitActivityCount;

    @OnClick({R2.id.xintuiLayout, R2.id.phoneLayout, R2.id.xintuiPasswordLayout, R2.id.xintuiSecurityLayout, R2.id.xintuiWeiXinLayout})
    public void onViewClicked(View view) {
        try {
            int id = view.getId();
            if (id == R.id.xintuiLayout) {// 信推号
            } else if (id == R.id.phoneLayout) {// 手机号
                bindPhoneReq();
            } else if (id == R.id.xintuiPasswordLayout) {// 信推密码
                if (firstBindPhoneNumberCheck(0)) {
                    return;
                }
                if (!limitActivityCount) {
                    limitActivityCount = true;
                    Intent modifypw = new Intent(this, ModifyPasswordActivity.class);
                    modifypw.putExtra("userInfo", userInfo);
                    modifypw.putExtra("havaPassword", securityStatus.checkExistsPassword == 1);
                    startActivityForResult(modifypw, REQUEST_MODIFY_PASSWORD);
                }
            } else if (id == R.id.xintuiSecurityLayout) {// 密保问题
                if (firstBindPhoneNumberCheck(1)) {
                    return;
                }
                if (!limitActivityCount) {
                    limitActivityCount = true;
                    Intent securityQues = new Intent(this, SetSecurityQuestionActivity.class);
                    securityQues.putExtra("_userInfo", userInfo);
                    securityQues.putExtra("havaSecurityQuestions", securityStatus.checkExistsEncrypted == 1);
                    startActivityForResult(securityQues, REQUEST_SET_SECURITY_QUESTION);
                }
            } else if (id == R.id.xintuiWeiXinLayout) {// 微信号
                if (firstBindPhoneNumberCheck(2)) {
                    return;
                }
                if (securityStatus.checkBindWX == 1) {
                    TipDialog.showCustomDialog(AccountSecurityActivity.this, getString(R.string.wendy_title), getString(R.string.exchange_bind_weixin_number),
                            new String[]{getString(R.string.confirm), getString(R.string.cancle_but)}, CustomAppUIDialog.TYPE_CONFIRM_CANCLE, true, 2, true,
                            new TipDialog.OnMsgTipDialogListener() {
                                @Override
                                public void then(boolean confirm, boolean outtouch) {
                                    if (confirm) {
                                        bindWeiXinRequested = true;
                                        bindWeiXinRequest.pullWeiXinAuth();
                                    }
                                }
                            });
                } else {
                    bindWeiXinRequested = true;
                    bindWeiXinRequest.pullWeiXinAuth();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_BIND_PHONE) {
            if (resultCode == Activity.RESULT_OK) {
                // 绑定手机号返回结果
                if (data != null) {
                    boolean bindResult = data.getBooleanExtra("bind_result", false);
                    if (bindResult) {
                        requestStatus();
                    }
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void bindWX(boolean success, String message) {
        if (success) {
            requestStatus();
            ToastTip.tip(getString(R.string.bind_weixin_success));
        } else {
            ToastTip.tip("" + message);
        }
    }

}

